package com.lifeverse.factory.type;

import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.LifeEntityType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 混合生命体创建器
 * 专门创建混合类型的生命体，支持从多个生命体融合创建
 */
@Slf4j
@Component
public class HybridLifeEntityCreator implements LifeEntityCreator {
    
    @Override
    public LifeEntity create(String name, String description, Map<String, Object> configuration) {
        log.info("Creating hybrid life entity: {}", name);
        
        LifeEntity entity = new LifeEntity();
        entity.setType(LifeEntityType.HYBRID);
        
        // 设置混合生命体特有的初始属性
        setupHybridAttributes(entity, configuration);
        
        return entity;
    }
    
    /**
     * 从多个生命体融合创建混合生命体
     * 
     * @param name 混合生命体名称
     * @param description 描述
     * @param sourceEntities 源生命体列表
     * @param fusionConfiguration 融合配置
     * @return 混合生命体实例
     */
    public LifeEntity createFromFusion(String name, String description, 
                                     List<LifeEntity> sourceEntities, 
                                     Map<String, Object> fusionConfiguration) {
        log.info("Creating hybrid life entity from fusion: {} with {} source entities", name, sourceEntities.size());
        
        LifeEntity hybridEntity = new LifeEntity();
        hybridEntity.setType(LifeEntityType.HYBRID);
        
        // 设置融合生成的属性
        setupFusionAttributes(hybridEntity, sourceEntities, fusionConfiguration);
        
        return hybridEntity;
    }
    
    @Override
    public LifeEntity clone(LifeEntity originalEntity, String newName, double variationLevel) {
        log.info("Cloning hybrid life entity: {} to {}", originalEntity.getName(), newName);
        
        LifeEntity clonedEntity = new LifeEntity();
        clonedEntity.setType(LifeEntityType.HYBRID);
        
        // 复制原始混合生命体的属性
        copyHybridAttributes(clonedEntity, originalEntity);
        
        return clonedEntity;
    }
    
    @Override
    public boolean validateConfiguration(Map<String, Object> configuration) {
        if (configuration == null) {
            return true; // 允许空配置，使用默认值
        }
        
        // 验证混合生命体特有配置
        if (configuration.containsKey("fusionTypes")) {
            Object fusionTypes = configuration.get("fusionTypes");
            if (!(fusionTypes instanceof List)) {
                return false;
            }
        }
        
        if (configuration.containsKey("synergyLevel")) {
            Object synergy = configuration.get("synergyLevel");
            if (!(synergy instanceof Number)) {
                return false;
            }
            double value = ((Number) synergy).doubleValue();
            if (value < 0 || value > 100) {
                return false;
            }
        }
        
        if (configuration.containsKey("stabilityFactor")) {
            Object stability = configuration.get("stabilityFactor");
            if (!(stability instanceof Number)) {
                return false;
            }
            double value = ((Number) stability).doubleValue();
            if (value < 0 || value > 1) {
                return false;
            }
        }
        
        return true;
    }
    
    @Override
    public Map<String, Object> getDefaultConfiguration() {
        return Map.of(
                "fusionTypes", List.of("CORPORATE", "URBAN"),
                "synergyLevel", 75.0, // 协同效应水平
                "stabilityFactor", 0.8, // 稳定性因子
                "adaptabilityBonus", 20.0, // 适应性加成
                "complexityTolerance", 85.0, // 复杂性容忍度
                "integrationDepth", "Deep", // 集成深度
                "emergentCapabilities", List.of("cross_domain_thinking", "adaptive_problem_solving"),
                "fusionStrategy", "Balanced" // 融合策略
        );
    }
    
    /**
     * 设置混合生命体特有属性
     */
    private void setupHybridAttributes(LifeEntity entity, Map<String, Object> configuration) {
        Map<String, Object> config = configuration != null ? configuration : getDefaultConfiguration();
        
        // 根据融合类型设置基础属性
        @SuppressWarnings("unchecked")
        List<String> fusionTypes = (List<String>) config.getOrDefault("fusionTypes", List.of("CORPORATE", "URBAN"));
        setupFusionTypeAttributes(entity, fusionTypes);
        
        // 根据协同水平调整能力
        double synergyLevel = ((Number) config.getOrDefault("synergyLevel", 75.0)).doubleValue();
        applySynergyBonus(entity, synergyLevel);
        
        // 根据稳定性因子调整健康度
        double stabilityFactor = ((Number) config.getOrDefault("stabilityFactor", 0.8)).doubleValue();
        adjustHealthByStability(entity, stabilityFactor);
        
        // 混合生命体通常具有高适应性和复杂性处理能力
        entity.setCreativityScore(BigDecimal.valueOf(80.0));
        entity.setWisdomScore(BigDecimal.valueOf(85.0));
        entity.setCollaborationScore(BigDecimal.valueOf(90.0)); // 融合多种能力，协作能力强
    }
    
    /**
     * 设置融合生成的属性
     */
    private void setupFusionAttributes(LifeEntity hybridEntity, List<LifeEntity> sourceEntities, 
                                     Map<String, Object> fusionConfiguration) {
        if (sourceEntities.isEmpty()) {
            throw new IllegalArgumentException("Source entities cannot be empty for fusion");
        }
        
        // 计算各项能力的融合值
        BigDecimal fusedWisdom = calculateFusedAttribute(sourceEntities, LifeEntity::getWisdomScore);
        BigDecimal fusedCreativity = calculateFusedAttribute(sourceEntities, LifeEntity::getCreativityScore);
        BigDecimal fusedCollaboration = calculateFusedAttribute(sourceEntities, LifeEntity::getCollaborationScore);
        BigDecimal fusedEnergy = calculateFusedAttribute(sourceEntities, LifeEntity::getEnergyLevel);
        BigDecimal fusedHealth = calculateFusedAttribute(sourceEntities, LifeEntity::getHealthScore);
        
        // 应用融合加成
        double fusionBonus = getFusionBonus(sourceEntities, fusionConfiguration);
        
        hybridEntity.setWisdomScore(fusedWisdom.multiply(BigDecimal.valueOf(fusionBonus)));
        hybridEntity.setCreativityScore(fusedCreativity.multiply(BigDecimal.valueOf(fusionBonus)));
        hybridEntity.setCollaborationScore(fusedCollaboration.multiply(BigDecimal.valueOf(fusionBonus)));
        hybridEntity.setEnergyLevel(fusedEnergy.multiply(BigDecimal.valueOf(0.9))); // 融合消耗一些能量
        hybridEntity.setHealthScore(fusedHealth.multiply(BigDecimal.valueOf(0.95))); // 融合可能影响稳定性
        
        // 设置融合特有的高级能力
        applyEmergentCapabilities(hybridEntity, sourceEntities);
    }
    
    /**
     * 根据融合类型设置属性
     */
    private void setupFusionTypeAttributes(LifeEntity entity, List<String> fusionTypes) {
        // 根据融合的类型数量和种类调整属性
        int typeCount = fusionTypes.size();
        double diversityBonus = Math.min(1.0 + (typeCount - 1) * 0.1, 1.5); // 最多50%加成
        
        // 基础属性设置
        entity.setCreativityScore(BigDecimal.valueOf(70.0 * diversityBonus));
        entity.setWisdomScore(BigDecimal.valueOf(75.0 * diversityBonus));
        entity.setCollaborationScore(BigDecimal.valueOf(80.0 * diversityBonus));
        entity.setEnergyLevel(BigDecimal.valueOf(85.0));
        entity.setHealthScore(BigDecimal.valueOf(90.0));
        
        // 根据具体融合类型进行微调
        for (String type : fusionTypes) {
            adjustAttributesByFusionType(entity, type);
        }
    }
    
    /**
     * 根据单个融合类型调整属性
     */
    private void adjustAttributesByFusionType(LifeEntity entity, String fusionType) {
        switch (fusionType.toUpperCase()) {
            case "CORPORATE" -> {
                entity.setWisdomScore(entity.getWisdomScore().multiply(BigDecimal.valueOf(1.1)));
                entity.setCollaborationScore(entity.getCollaborationScore().multiply(BigDecimal.valueOf(1.05)));
            }
            case "URBAN" -> {
                entity.setCollaborationScore(entity.getCollaborationScore().multiply(BigDecimal.valueOf(1.15)));
                entity.setHealthScore(entity.getHealthScore().multiply(BigDecimal.valueOf(1.05)));
            }
            case "CONCEPTUAL" -> {
                entity.setCreativityScore(entity.getCreativityScore().multiply(BigDecimal.valueOf(1.2)));
                entity.setWisdomScore(entity.getWisdomScore().multiply(BigDecimal.valueOf(1.1)));
            }
            case "INDIVIDUAL" -> {
                entity.setCreativityScore(entity.getCreativityScore().multiply(BigDecimal.valueOf(1.05)));
                entity.setEnergyLevel(entity.getEnergyLevel().multiply(BigDecimal.valueOf(1.1)));
            }
            case "SYSTEM" -> {
                entity.setWisdomScore(entity.getWisdomScore().multiply(BigDecimal.valueOf(1.05)));
                entity.setEnergyLevel(entity.getEnergyLevel().multiply(BigDecimal.valueOf(1.15)));
            }
        }
    }
    
    /**
     * 应用协同加成
     */
    private void applySynergyBonus(LifeEntity entity, double synergyLevel) {
        double synergyMultiplier = 1.0 + (synergyLevel / 100.0) * 0.3; // 最多30%加成
        
        entity.setCreativityScore(entity.getCreativityScore().multiply(BigDecimal.valueOf(synergyMultiplier)));
        entity.setWisdomScore(entity.getWisdomScore().multiply(BigDecimal.valueOf(synergyMultiplier)));
        entity.setCollaborationScore(entity.getCollaborationScore().multiply(BigDecimal.valueOf(synergyMultiplier)));
    }
    
    /**
     * 根据稳定性调整健康度
     */
    private void adjustHealthByStability(LifeEntity entity, double stabilityFactor) {
        BigDecimal healthMultiplier = BigDecimal.valueOf(stabilityFactor);
        entity.setHealthScore(entity.getHealthScore().multiply(healthMultiplier));
    }
    
    /**
     * 计算融合属性值
     */
    private BigDecimal calculateFusedAttribute(List<LifeEntity> sourceEntities, 
                                             java.util.function.Function<LifeEntity, BigDecimal> attributeExtractor) {
        // 使用加权平均，考虑各生命体的健康度作为权重
        BigDecimal totalWeightedValue = BigDecimal.ZERO;
        BigDecimal totalWeight = BigDecimal.ZERO;
        
        for (LifeEntity entity : sourceEntities) {
            BigDecimal weight = entity.getHealthScore().divide(BigDecimal.valueOf(100), 4, java.math.RoundingMode.HALF_UP);
            BigDecimal value = attributeExtractor.apply(entity);
            
            totalWeightedValue = totalWeightedValue.add(value.multiply(weight));
            totalWeight = totalWeight.add(weight);
        }
        
        if (totalWeight.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        
        return totalWeightedValue.divide(totalWeight, 2, java.math.RoundingMode.HALF_UP);
    }
    
    /**
     * 获取融合加成
     */
    private double getFusionBonus(List<LifeEntity> sourceEntities, Map<String, Object> fusionConfiguration) {
        // 基础融合加成
        double baseBonus = 1.2;
        
        // 根据源生命体的多样性增加加成
        long uniqueTypes = sourceEntities.stream()
                .map(LifeEntity::getType)
                .distinct()
                .count();
        double diversityBonus = 1.0 + (uniqueTypes - 1) * 0.05; // 每种额外类型5%加成
        
        // 根据融合配置调整
        String fusionStrategy = (String) fusionConfiguration.getOrDefault("fusionStrategy", "Balanced");
        double strategyMultiplier = switch (fusionStrategy.toLowerCase()) {
            case "aggressive" -> 1.3;
            case "conservative" -> 1.1;
            case "balanced" -> 1.2;
            default -> 1.2;
        };
        
        return baseBonus * diversityBonus * strategyMultiplier;
    }
    
    /**
     * 应用涌现能力
     */
    private void applyEmergentCapabilities(LifeEntity hybridEntity, List<LifeEntity> sourceEntities) {
        // 根据源生命体的组合产生新的涌现能力
        // 这里可以实现复杂的涌现逻辑
        
        // 如果包含概念生命体和企业生命体，增强创新能力
        boolean hasConceptual = sourceEntities.stream().anyMatch(e -> e.getType() == LifeEntityType.CONCEPTUAL);
        boolean hasCorporate = sourceEntities.stream().anyMatch(e -> e.getType() == LifeEntityType.CORPORATE);
        
        if (hasConceptual && hasCorporate) {
            hybridEntity.setCreativityScore(hybridEntity.getCreativityScore().multiply(BigDecimal.valueOf(1.25)));
        }
        
        // 如果包含城市生命体和系统生命体，增强协作能力
        boolean hasUrban = sourceEntities.stream().anyMatch(e -> e.getType() == LifeEntityType.URBAN);
        boolean hasSystem = sourceEntities.stream().anyMatch(e -> e.getType() == LifeEntityType.SYSTEM);
        
        if (hasUrban && hasSystem) {
            hybridEntity.setCollaborationScore(hybridEntity.getCollaborationScore().multiply(BigDecimal.valueOf(1.2)));
        }
    }
    
    /**
     * 复制混合生命体属性
     */
    private void copyHybridAttributes(LifeEntity clonedEntity, LifeEntity originalEntity) {
        // 复制基本属性
        clonedEntity.setWisdomScore(originalEntity.getWisdomScore());
        clonedEntity.setCreativityScore(originalEntity.getCreativityScore());
        clonedEntity.setCollaborationScore(originalEntity.getCollaborationScore());
        clonedEntity.setEnergyLevel(originalEntity.getEnergyLevel());
        clonedEntity.setHealthScore(originalEntity.getHealthScore());
        
        // 复制配置信息
        clonedEntity.setConfiguration(originalEntity.getConfiguration());
    }
}